﻿Imports System.Management

Public Class GetUptime
    Public Shared Function GetUptime(ByVal strcomputer As String) As String
        Dim wmiScope As ManagementScope
        Dim wmiConnectionOptions As New ConnectionOptions
        Dim query As ManagementObjectSearcher
        Dim queryCollection As ManagementObjectCollection
        Dim oq As ObjectQuery
        Dim perftimestamp As String = ""
        Dim perttimefreq As String = ""
        Dim counter As String = ""
        ' ReSharper disable once RedundantAssignment
        Dim iUptimeInSec As Long = 0
        With wmiConnectionOptions
            .Impersonation = ImpersonationLevel.Impersonate
            .Authentication = AuthenticationLevel.Packet
        End With
        Try
            wmiScope = New ManagementScope("\\" & strcomputer & "\root\cimv2", wmiConnectionOptions)

            oq = New ObjectQuery("select * from Win32_PerfRawData_PerfOS_System")
            query = New ManagementObjectSearcher(wmiScope, oq)
            queryCollection = query.Get()
            For Each oReturn As ManagementObject In queryCollection
                perftimestamp = oReturn("Timestamp_Object").ToString()
                perttimefreq = oReturn("Frequency_Object").ToString()
                counter = oReturn("SystemUpTime").ToString()
            Next
            ' Calculation in seconds:
            iUptimeInSec = Convert.ToInt64((Double.Parse(perftimestamp) - Double.Parse(counter)) / Double.Parse(perttimefreq))
            ' convert the seconds
            Return ConvertTime.ConvertTime(iUptimeInSec)
        Catch
            Return "Machine is inaccessable"
        End Try

    End Function
End Class
